import React, { useState, useEffect } from 'react'
import { Card, Button, Input, Select, Switch, TreeSelect } from "antd"
import { BorderOutlined } from '@ant-design/icons';
import type { TreeSelectProps } from 'antd';
import { Image, Upload } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import { useSnapshot } from 'valtio';
import { order } from '@/stores/Order';
import { useNavigate } from 'react-router-dom';
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
const getBase64 = (file: FileType): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
    });
export default function Productshow() {
    const { TextArea } = Input;
    const store = useSnapshot(order)
    const handleChanges = (value: string) => {
        setentity(value)
    };
    useEffect(() => {
            setname(store.dateedit.name),
            setshopname(store.dateedit.shopname),
            setshopcode(store.dateedit.shopcode),
            settypes(store.dateedit.types.title)
            setentity(store.dateedit.entity),
            settext(store.dateedit.text),
            setprice(store.dateedit.price),
            setvipprice(store.dateedit.vipprice),
            setcost(store.dateedit.cost),
            setboxfee(store.dateedit.boxfee),
            setstate(store.dateedit.state)
    }, [])
    const weioptions = [
        { value: '份', label: '份' },
        { value: '盘', label: '盘' },
        { value: '个', label: '个' },
        { value: '瓶', label: '瓶' },
        { value: '斤', label: '斤' },
        { value: '升', label: '升' },
        { value: '毫升', label: '毫升' },
        { value: '克', label: '克' },
    ]
    const treeData = store.treedata
    const onChange = (newValue: string) => {
        settypes(newValue)
    };
    const onPopupScroll: TreeSelectProps['onPopupScroll'] = (e) => {
        console.log('onPopupScroll', e);
    };
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [fileList, setFileList] = useState<UploadFile[]>([
        {
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
        },

    ]);
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as FileType);
        }
        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
    };
    const handleChangeimg: UploadProps['onChange'] = ({ fileList: newFileList }) => {
        setFileList(newFileList);
    }
    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            <BorderOutlined />
            <div style={{ marginTop: 8 }}>上传图片</div>
        </button>
    );
    const onChangetext = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        settext(e.target.value)
    };
    const onChangestate = (checked: boolean) => {
        setstate(checked)
    };
    const [name, setname] = useState('')
    const [shopname, setshopname] = useState('')
    const [shopcode, setshopcode] = useState('')
    const [types, settypes] = useState('')
    const [entity, setentity] = useState('')
    const [price, setprice] = useState("")
    const [vipprice, setvipprice] = useState("")
    const [cost, setcost] = useState("")
    const [text, settext] = useState("")
    const [boxfee, setboxfee] = useState("")
    const [state, setstate] = useState(false)
    const nav = useNavigate()

    return (
        <div>
            <Card bodyStyle={{ padding: 0 }} className='w-[90%] m-auto mt-5 h-[100vh] p-0' >
                <header className='p-0 pl-3 h-[35px] bg-#eee text-[20px] item-center'>商品参数</header>
                <div className='m-auto w-[50%] items-center'>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>所属店铺：</p><Input value={name} onChange={(e) => {
                        setname(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>商品名称：</p><Input value={shopname} onChange={(e) => {
                        setshopname(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>店铺编码：</p><Input value={shopcode} onChange={(e) => {
                        setshopcode(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>商品分类：</p> <TreeSelect
                        showSearch
                        style={{ width: 360, marginTop: 10 }}
                        value={types}
                        fieldNames={{ label: 'title', value: '_id', children: 'children' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="Please select"
                        allowClear
                        treeDefaultExpandAll
                        onChange={onChange}
                        treeData={treeData}
                        onPopupScroll={onPopupScroll}
                    /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>商品单位：</p><Select
                        defaultValue="lucy"
                        value={entity}
                        style={{ width: 360 }}
                        onChange={handleChanges}
                        options={weioptions}
                    /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>堂食价：</p><Input value={price} onChange={(e) => {
                        setprice(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>会员价：</p><Input value={vipprice} onChange={(e) => {
                        setvipprice(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>外卖价：</p><Input value={cost} onChange={(e) => {
                        setcost(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>餐盒费价：</p><Input value={boxfee} onChange={(e) => {
                        setboxfee(e.target.value)
                    }} className='max-w-[360px] h-[30px]' type="text" /></div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>商品图片：</p>
                        <Upload
                            action="http://127.0.0.1:3000/upload"
                            listType="picture-card"
                            fileList={fileList}
                            onPreview={handlePreview}
                            onChange={handleChangeimg}
                        >
                            {fileList.length >= 8 ? null : uploadButton}
                        </Upload>
                        {previewImage && (
                            <Image
                                wrapperStyle={{ display: 'none' }}
                                preview={{
                                    visible: previewOpen,
                                    onVisibleChange: (visible) => setPreviewOpen(visible),
                                    afterOpenChange: (visible) => !visible && setPreviewImage(''),
                                }}
                                src={previewImage}
                            />
                        )}

                    </div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>餐盒费价：</p>
                        <TextArea
                            showCount
                            maxLength={100}
                            value={text}
                            onChange={onChangetext}
                            placeholder="disable resize"
                            style={{ height: 120, resize: 'none' }}
                        />
                    </div>
                    <div className='flex items-center w-[100%] mt-[10px]'><p className='w-[90px]'>上架状态：</p><Switch defaultChecked value={state} onChange={onChangestate} /></div>
                </div>
                <footer className='w-[90%]   h-[55px]  text-[20px] m-auto mt-20 item-center'>
                    <div className='w-[100%] flex justify-end'>
                        <Button className='mr-5' onClick={() => {
                            nav(-1)
                        }}>取消</Button>
                        <Button type="primary" onClick={() => {
                            store.sendUpdate("这是成功")
                            store.editpro({ _id: store.dateedit._id,shopcode:shopcode, name: name, shopname: shopname, price: price, vipprice: vipprice, cost: cost, boxfee: boxfee, text: text, state: state })
                            nav(-1)
                        }}>确定</Button>
                    </div>
                </footer>
            </Card>

        </div>
    )
}
